﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using Guline.Web.Central.Controllers;
using Guline.Web.CentralModels.Object;
namespace Guline.Web.Central.Areas.Api.Controllers
{
    public class UserController : BaseController
    {
        public ActionResult Login(string username, string password)
        {
            if (WebSecurity.Login(username, password, false))
            {
                var user = db.Accounts.Where(m=>m.UserName==username).FirstOrDefault();
                var apps = from m in db.CApps where m.Account.UserName == username select new { m.Accesskey, m.CreateDate, m.Description, m.ID, m.Name, m.DeviceID, m.Device.AndroidID};
                return Json(new { success = true, info = new {user.UserName,user.DisplayName,user.Email,user.Gender,user.Phone,user.BirthDay,user.ID,Apps=user.CApps.Count},data=apps.FirstOrDefault() }, JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { success = false },JsonRequestBehavior.AllowGet);

        }
        public ActionResult LoginAndroid(string username, string password, string AndroidID, string AndroidName, string PhoneNumber)
        {
            if (WebSecurity.Login(username, password, false))
            {
                var user = db.Accounts.Where(m => m.UserName == username).FirstOrDefault();
                var apps = from m in db.CApps where m.Account.UserName == username select new { m.Accesskey, m.CreateDate, m.Description, m.ID, m.Name, m.DeviceID, m.Device.AndroidID };
                var dv = db.Devices.Where(m => m.AndroidID == AndroidID).FirstOrDefault();
                if (dv == null)
                {
                    dv = new Device();
                    dv.Status = 1;
                    dv.Name = AndroidName;
                    dv.AccountID = user.ID;
                    dv.AndroidID = AndroidID;
                    dv.DateCreated = DateTime.Now;
                    dv.DateLastedOnline = DateTime.Now;
                    dv.Enable = true;
                    dv.PhoneNumber = PhoneNumber;
                    db.Devices.Add(dv);
                }
                else
                {
                    dv.Status = 1;
                }
                db.SaveChanges();
                return Json(new { success = true, info = new { user.UserName, user.DisplayName, user.Email, user.Gender, user.Phone, user.BirthDay, user.ID, Apps = user.CApps.Count }, data = apps.FirstOrDefault() }, JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { success = false }, JsonRequestBehavior.AllowGet);

        }
    }
}
